<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户" prop="userId">
            <el-select
              v-model="formData.userId"
              placeholder="请选择用户"
              filterable
              remote
              :remote-method="searchUsers"
              :loading="userLoading"
              clearable
              class="w-full"
            >
              <el-option
                v-for="user in userOptions"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证书编号" prop="certificateNumber">
            <el-input v-model="formData.certificateNumber" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职业代码" prop="professionCodes">
            <el-input v-model="formData.professionCodes" placeholder="请输入职业代码，多个用逗号分隔" />
            <div class="text-xs text-gray-500 mt-1">
              常用：6-31-01-06(软件设计师)、6-31-01-03(电工)
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="技能等级" prop="skillLevels">
            <el-checkbox-group v-model="selectedSkillLevels">
              <el-checkbox value="五级">五级</el-checkbox>
              <el-checkbox value="四级">四级</el-checkbox>
              <el-checkbox value="三级">三级</el-checkbox>
              <el-checkbox value="二级">二级</el-checkbox>
              <el-checkbox value="一级">一级</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发证机构" prop="certificateIssuer">
            <el-select
              v-model="formData.certificateIssuer"
              placeholder="请选择发证机构"
              filterable
              allow-create
              clearable
              class="w-full"
            >
              <el-option
                v-for="issuer in certificateIssuers"
                :key="issuer.value"
                :label="issuer.label"
                :value="issuer.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发证日期" prop="certificateDate">
            <el-date-picker
              v-model="formData.certificateDate"
              type="date"
              placeholder="选择发证日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="有效期至" prop="validUntil">
            <el-date-picker
              v-model="formData.validUntil"
              type="date"
              placeholder="选择有效期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专业领域" prop="specialties">
            <el-input v-model="formData.specialties" placeholder="请输入专业领域，多个用逗号分隔" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最大工作负荷" prop="maxWorkload">
            <el-input-number
              v-model="formData.maxWorkload"
              :min="1"
              :max="100"
              placeholder="请输入最大工作负荷"
              class="w-full"
            />
            <div class="text-xs text-gray-500 mt-1">单位：人次/月</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资质状态" prop="qualificationStatus">
            <el-radio-group v-model="formData.qualificationStatus">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import * as EvaluatorApi from '@/api/eval/evaluator'
import * as UserApi from '@/api/system/user'

const { t } = useI18n()
const message = useMessage()

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const dialogTitle = computed(() => (formData.value.id ? '修改考评员资质' : '新增考评员资质'))
const formLoading = ref(false)
const formRef = ref()

// 用户选择相关
const userLoading = ref(false)
const userOptions = ref<any[]>([])

// 技能等级选择
const selectedSkillLevels = ref<string[]>(['五级', '四级', '三级'])

// 发证机构选项
const certificateIssuers = ref([
  { label: '广东省人力资源和社会保障厅', value: '广东省人力资源和社会保障厅' },
  { label: '人力资源和社会保障部', value: '人力资源和社会保障部' },
  { label: '国家人力资源和社会保障部', value: '国家人力资源和社会保障部' },
  { label: '中华人民共和国人力资源和社会保障部', value: '中华人民共和国人力资源和社会保障部' },
  { label: '广州市人力资源和社会保障局', value: '广州市人力资源和社会保障局' },
  { label: '深圳市人力资源和社会保障局', value: '深圳市人力资源和社会保障局' },
  { label: '东莞市人力资源和社会保障局', value: '东莞市人力资源和社会保障局' },
  { label: '佛山市人力资源和社会保障局', value: '佛山市人力资源和社会保障局' },
  { label: '中山市人力资源和社会保障局', value: '中山市人力资源和社会保障局' },
  { label: '珠海市人力资源和社会保障局', value: '珠海市人力资源和社会保障局' },
  { label: '惠州市人力资源和社会保障局', value: '惠州市人力资源和社会保障局' },
  { label: '江门市人力资源和社会保障局', value: '江门市人力资源和社会保障局' },
  { label: '肇庆市人力资源和社会保障局', value: '肇庆市人力资源和社会保障局' },
  { label: '汕头市人力资源和社会保障局', value: '汕头市人力资源和社会保障局' },
  { label: '湛江市人力资源和社会保障局', value: '湛江市人力资源和社会保障局' },
  { label: '茂名市人力资源和社会保障局', value: '茂名市人力资源和社会保障局' },
  { label: '梅州市人力资源和社会保障局', value: '梅州市人力资源和社会保障局' },
  { label: '汕尾市人力资源和社会保障局', value: '汕尾市人力资源和社会保障局' },
  { label: '河源市人力资源和社会保障局', value: '河源市人力资源和社会保障局' },
  { label: '阳江市人力资源和社会保障局', value: '阳江市人力资源和社会保障局' },
  { label: '清远市人力资源和社会保障局', value: '清远市人力资源和社会保障局' },
  { label: '潮州市人力资源和社会保障局', value: '潮州市人力资源和社会保障局' },
  { label: '揭阳市人力资源和社会保障局', value: '揭阳市人力资源和社会保障局' },
  { label: '云浮市人力资源和社会保障局', value: '云浮市人力资源和社会保障局' }
])

// 表单数据
const formData = ref({
  id: undefined,
  userId: undefined,
  professionCodes: '6-31-01-06',
  skillLevels: '',
  certificateNumber: '',
  certificateIssuer: '广东省人力资源和社会保障厅',
  certificateDate: '',
  validUntil: '',
  specialties: '通用技能',
  maxWorkload: 15,
  qualificationStatus: 1
})

// 监听技能等级选择变化
watch(selectedSkillLevels, (newVal) => {
  formData.value.skillLevels = newVal.join(',')
}, { immediate: true })

// 表单验证规则
const formRules = ref({
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  professionCodes: [{ required: true, message: '职业代码不能为空', trigger: 'blur' }],
  certificateIssuer: [{ required: true, message: '发证机构不能为空', trigger: 'blur' }],
  certificateDate: [{ required: true, message: '发证日期不能为空', trigger: 'change' }],
  validUntil: [{ required: true, message: '有效期不能为空', trigger: 'change' }],
  qualificationStatus: [{ required: true, message: '资质状态不能为空', trigger: 'change' }]
})

// 日期格式化函数 - 将数组格式转换为字符串格式
const formatDateForInput = (dateValue: any): string => {
  if (!dateValue) {
    return ''
  }

  // 如果是数组格式 [year, month, day]
  if (Array.isArray(dateValue) && dateValue.length >= 3) {
    const [year, month, day] = dateValue
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  }

  // 如果是字符串且已经是 YYYY-MM-DD 格式，直接返回
  if (typeof dateValue === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
    return dateValue
  }

  // 其他格式尝试转换
  if (typeof dateValue === 'string' || typeof dateValue === 'number') {
    const date = new Date(dateValue)
    if (!isNaN(date.getTime())) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }

  return ''
}

// 搜索用户
const searchUsers = async (query: string) => {
  if (!query) {
    userOptions.value = []
    return
  }

  userLoading.value = true
  try {
    const data = await UserApi.getUserPage({
      pageNo: 1,
      pageSize: 20,
      nickname: query
    })
    userOptions.value = data.list || []
  } catch (error) {
    console.error('搜索用户失败:', error)
  } finally {
    userLoading.value = false
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await EvaluatorApi.getEvaluatorQualification(id)

      // 先赋值基本字段（排除日期字段）
      const { certificateDate, validUntil, ...otherData } = data
      Object.assign(formData.value, otherData)

      // 处理日期字段格式转换
      if (certificateDate) {
        formData.value.certificateDate = formatDateForInput(certificateDate)
      }

      if (validUntil) {
        formData.value.validUntil = formatDateForInput(validUntil)
      }

      // 设置技能等级选择
      if (data.skillLevels) {
        selectedSkillLevels.value = data.skillLevels.split(',')
      }

      console.log('最终表单数据:', formData.value) // 调试日志
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = { ...formData.value }

    if (data.id) {
      await EvaluatorApi.updateEvaluatorQualification(data)
      message.success('修改成功')
    } else {
      await EvaluatorApi.createEvaluatorQualification(data)
      message.success('新增成功')
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    professionCodes: '6-31-01-06',
    skillLevels: '',
    certificateNumber: '',
    certificateIssuer: '广东省人力资源和社会保障厅',
    certificateDate: '',
    validUntil: '',
    specialties: '通用技能',
    maxWorkload: 15,
    qualificationStatus: 1
  }
  selectedSkillLevels.value = ['五级', '四级', '三级']
  userOptions.value = []
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

defineExpose({ open })
</script>
